<template>
	<view class="sleep" :style="{paddingTop: paddingHeight + 'px'}">
		<nav-bar title="睡眠" backgroundColor="#FAFAFA"></nav-bar>
		<view class="m-container">
			<view class="top_view">
				<view class="date_h">
					<u-image width="48rpx" height="48rpx" :showMenuByLongpress="false"
						@click="$u.throttle(dayReduceTap, 1000)"
						src="http://oss.antaimedical.com/images/static/2024/07/6690f721eb14d0f049f44d4fjy4xzrYAJBuG7f1f413ee9db0c4a498e3ad8017621b0.png"
						:lazy-load="true"></u-image>
					<view class="date_m" @click="showCalendar_ = true">
						<text>{{ currentSearchTime }}</text>
						<text class="iconfont icon-ln_sanjiaoxia"></text>
					</view>
					<u-image width="48rpx" height="48rpx" :showMenuByLongpress="false"
						@click="$u.throttle(dayPlusTap, 1000)"
						src="http://oss.antaimedical.com/images/static/2024/07/6690f735eb14d0f049f44d50JLzReaiikJTQc2681661f1bb789352b3fc054979635a.png"
						:lazy-load="true"></u-image>
				</view>
			</view>
			<view class="o_s_card" v-if="sleepInfo.afterId">
				<view class="info">
					<view class="public i_l">
						<view class="time">
							{{ sleepInfo.duration }}
						</view>
						<view class="border"></view>
					</view>
					<view class="public i_m">
						<view class="meal_b">
							<view class="bar" v-if="sleepInfo.rerLevelFront"
								:style="{height: getHeight(sleepInfo.rerLevelFront),backgroundColor: getBgColor(sleepInfo.rerLevelFront)}">
								<text>{{ sleepInfo.rerLevelFront }}</text>
							</view>
							<view class="text">
								睡前
							</view>
						</view>
						<view class="meal_a">
							<view class="bar" v-if="sleepInfo.rerLevelAfter"
								:style="{height: getHeight(sleepInfo.rerLevelAfter),backgroundColor: getBgColor(sleepInfo.rerLevelAfter)}">
								<text>{{ sleepInfo.rerLevelAfter }}</text>
							</view>
							<view class="text">
								睡后
							</view>
						</view>
					</view>
					<view class="public i_r">
						<view class="border"></view>
						<view class="main">
							<u-image width="48rpx" :showMenuByLongpress="false"
								v-if="sleepInfo.rerLevelFront && sleepInfo.rerLevelAfter" shape="circle" height="48rpx"
								:src="getStatusSrc(sleepInfo)" :lazy-load="true"></u-image>
						</view>
					</view>
				</view>
			</view>
			<view class="none" v-else>
				今日未记录
			</view>
			<view class="r-card">
				<view class="tabs">
					<view class="tab" @click="changeType(item.type)" :class="{current: currentType == item.type}"
						v-for="(item,index) in tabs" :key="index">
						{{ item.text }}
					</view>
				</view>
				<view class="date_h">
					<view class="pre_p" @click="$u.throttle(reduceTap, 1000)">
						<text class="iconfont icon-ln_sanjiaozuo"></text>
					</view>
					<view class="date_m" @click="showCalendar = true">
						<text>{{ currentChartsTime }}</text>
						<text class="iconfont icon-ln_sanjiaoxia"></text>
					</view>
					<view class="next_p" @click="$u.throttle(plusTap, 1000)">
						<text class="iconfont icon-ln_sanjiaoyou"></text>
					</view>
				</view>
				<view class="tooltip">
					<view class="t-l">
						<view class="mean_txt">日平均</view>
						<view class="mean">{{ meanSleep ? meanSleep : '无记录'}}</view>
					</view>
				</view>
				<view class="charts">
					<uni-ec-canvas class="uni-ec-canvas" canvas-id="sleep-charts" ref="sleep-charts"></uni-ec-canvas>
				</view>
				<view class="c_tips">
					<view class="current_modal">
						<view class="time">{{ currentDetails.date ? currentDetails.date : ''}}</view>
						<view class="data">{{ currentDetails.time ? currentDetails.time : ''}}</view>
					</view>
				</view>

			</view>
			<view class="a_cell" @click="goRecord">
				<text class="all">查看全部</text>
				<text class="iconfont icon-arrow_rigth"></text>
			</view>
		</view>
		<my-calendar :monthNum="36" :defaultDate="defaultDate" :maxDate="maxDate" @confirm="selectDate"
			:minDate="minDate" :show="showCalendar" color="#545DDE" closeOnClickOverlay
			@close="showCalendar = false"></my-calendar>
		<my-calendar :monthNum="36" :defaultDate="defaultDate_" :maxDate="maxDate" @confirm="selectDate_"
			:minDate="minDate" :show="showCalendar_" color="#545DDE" closeOnClickOverlay
			@close="showCalendar_ = false"></my-calendar>
	</view>
</template>

<script>
import myCalendar from '@/components/myCalendar/myCalendar.vue';
	import * as echarts from '@/components/uni-ec-canvas/echarts.min.js';
	import {
		findSleepCompare,
		findSleepPicture,
		findSleepAvg
	} from '@/api/index.js'
	import {
		getItemColor,
		getWeekDate
	} from '@/utils/utils.js'
	const dayjs = require('@/utils/dayjs.min.js');
	export default {
        components: {
            myCalendar,
        },
		data() {
			return {
				paddingHeight: uni.getStorageSync('navbarHeight'),
				userId: uni.getStorageSync("userId"),
				status: [
					'http://oss.antaimedical.com/images/static/2024/06/666d344deb14d0f049f44d19nLCYRs6gqIu4d1573ef1c4be017d029a0d1cb62ac5da.png',
					'http://oss.antaimedical.com/images/static/2024/06/666d345eeb14d0f049f44d1aI9xNeH4ts7a783b3687c40253ad9f251a61424486bd1.png',
					'http://oss.antaimedical.com/images/static/2024/06/666d346beb14d0f049f44d1bdZgMKnmb0iTS27b54b8d865ea7c86aae9f3165321820.png'
				],
				tabs: [{
						type: 1,
						text: '周'
					},
					{
						type: 2,
						text: '月'
					},
					{
						type: 3,
						text: '年'
					}
				],
				meanSleep: 0,
				currentType: 1,
				defaultDate: [],
				defaultDate_: [],
				maxDate: undefined,
				minDate: undefined,
				currentSearchTime: undefined, // 当前查询的时间
				currentChartsTime: undefined, // 当前图表查询时间
				xArr: [],
				chartsData: [], // 图表原始数据
				currentEventIndex: undefined, // 当前点击事件下标
				showDetails: false, // 图表点击展示总时长详情
				currentDetails: {},
				showCalendar: false, // 日历控件显示
				showCalendar_: false, // 日历控件显示
				dataList: [], // 某一天数据
				sleepInfo: {}
			}
		},
		filters: {
			comparisonFilte(info) {
				if (typeof info.rerLevelAfter !== 'number' || typeof info.rerLevelFront !== 'number') return '未形成对比'
				if (info.rerLevelAfter > info.rerLevelFront) {
					return '上升'
				} else if (info.rerLevelAfter === info.rerLevelFront) {
					return '持平'
				} else if (info.rerLevelAfter < info.rerLevelFront) {
					return '下降'
				}
			}
		},
		watch: {
			currentType(nVal, oVal) {
				this.currentDetails = {}
				if (nVal == 1) {
					this.currentChartsTime = getWeekDate(this.maxDate)
					this.defaultDate[0] = this.maxDate
				} else if (nVal == 2) {
					this.currentChartsTime = dayjs().format('YYYY/MM')
					this.defaultDate[0] = this.maxDate
				} else if (nVal == 3) {
					this.currentChartsTime = dayjs().format('YYYY')
					this.defaultDate[0] = this.maxDate
				}
				this.fetchData()
			}
		},
		onLoad() {
			this.maxDate = dayjs().format('YYYY-MM-DD');
			this.minDate = dayjs(dayjs(this.maxDate).subtract(2, 'year')).format('YYYY-MM-DD')
			this.currentSearchTime = dayjs().format('YYYY/MM/DD')
			this.currentChartsTime = getWeekDate(this.maxDate)
			this.defaultDate[0] = this.maxDate
			this.defaultDate_[0] = this.maxDate
		},
		onShow() {
			this.loadingData()
		},
		methods: {
			async loadingData() {
				uni.showLoading({
					title: '加载中...'
				})
				try {
					await this.fetchData(true)
					await this.fetchDayData(true)
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
				uni.hideLoading()
			},
			async fetchDayData(bol) {
				if (!bol) {
					uni.showLoading({
						title: '加载中...'
					})
				}
				let params = {
					userId: this.userId,
					time: this.defaultDate_[0]
				}
				try {
					const res = await findSleepCompare(params)
					if (res.code == 200) {
						let after = res.data.find(item => {
							return item.tag == 1
						})
						let front = res.data.find(item => {
							return item.tag == 7
						})
						this.sleepInfo = {
							rerLevelAfter: after.rerLevel,
							rerLevelFront: front.rerLevel,
							duration: after.duration,
							afterId: after.id,
							frontId: front.id,
						}
					}
				} catch (e) {
					//TODO handle the exception
				}
				if (!bol) {
					uni.hideLoading()
				}
			},
			// 查询数据
			async fetchData(bol) {
				if (!bol) {
					uni.showLoading({
						title: '加载中...'
					})
				}
				let params = {
					time: this.defaultDate[0],
					userId: this.userId,
					type: ''
				}
				if (this.currentType == 1) { // 查询某一周数据
					params.type = 'w'
				} else if (this.currentType == 2) { // 查询月数据
					params.type = 'm'
				} else if (this.currentType == 3) { // 查询年数据
					params.type = 'y'
				}
				try {
					const res = await findSleepAvg(params)
					const res_2 = await findSleepPicture(params)
					if (res.code == 200) {
						this.meanSleep = res.data
						if (this.currentType == 1) {
							this.xArr = ['一', '二', '三', '四', '五', '六', '日']
						} else if (this.currentType == 2) {
							this.xArr = res_2.data.map((item, index) => {
								return String(index + 1)
							})
						} else if (this.currentType == 3) {
							this.xArr = res_2.data.map((item, index) => {
								return String(index + 1)
							})
						}
						let arr = res_2.data.map(item => {
							return item.durationMinute
						})
						this.chartsData = res_2.data
						this.loadCharts(this.xArr, arr, this.currentType == 2 ? 'month' : 'other')
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
				if (!bol) {
					uni.hideLoading()
				}
			},
			loadCharts(xArr, arr, type) {
				this.$refs['sleep-charts'].init((canvas, width, height, dpr) => {
					const chart = echarts.init(canvas, null, {
						width,
						height,
						devicePixelRatio: dpr // new
					});
					chart.setOption(
						this.getOption(xArr, arr, type)
					);
					chart.on('click', 'series', (params) => {
						console.log('cartsclick', params)
						if (this.currentType == 3) {
							let time = this.chartsData[params.dataIndex].durationMinute
							let total;
							let hour;
							let minute;
							if (time < 60) {
								minute = time
								total = `${minute}分钟`
							} else if (time === 60) {
								total = `1小时0分钟`
							} else if (time >= 60) {
								hour = parseInt(time / 60)
								minute = parseInt(time % 60)
								total = `${hour}小时${minute}分钟`
							}
							this.currentDetails = {
								date: dayjs(this.chartsData[params.dataIndex].createTimeStr).format(
									'YYYY年MM月'),
								time: total
							}
						} else {
							let endTime = this.chartsData[params.dataIndex].endTime
							this.currentDetails = {
								date: dayjs(endTime).format('YYYY年MM月DD日'),
								time: this.chartsData[params.dataIndex].duration
							}
						}
					});
					return chart;
				});
			},
			// 上一个选项
			dayReduceTap() {
				let pre = dayjs(dayjs(this.currentSearchTime).subtract(1, 'day')).format('YYYY/MM/DD')
				let min = dayjs(this.minDate).format('YYYY/MM/DD')
				if (!dayjs(pre).isBefore(min)) { // 比对前一天是否是最小天数的前一天
					this.currentSearchTime = pre
					this.defaultDate_[0] = pre.replaceAll('/', '-')
					this.fetchDayData()
				} else {
					uni.showToast({
						title: '已经是最后一页',
						icon: 'none'
					})
				}
			},
			// 下一个选项
			dayPlusTap() {
				let next = dayjs(dayjs(this.currentSearchTime).add(1, 'day')).format('YYYY/MM/DD')
				let max = dayjs(this.maxDate).format('YYYY/MM/DD')
				if (!dayjs(next).isAfter(max)) { // 比对后一天是否是最大天数的后一天
					this.currentSearchTime = next
					this.defaultDate_[0] = next.replaceAll('/', '-')
					this.fetchDayData()
				} else {
					uni.showToast({
						title: '已经是最后一页',
						icon: 'none'
					})
				}
			},
			// 最大可选某天控件
			selectDate_(e) {
				this.currentSearchTime = e[0].replaceAll('-', '/')
				this.defaultDate_[0] = e[0]
				this.fetchDayData()
				this.showCalendar_ = false
			},
			// 选择日期
			selectDate(e) {
				this.defaultDate[0] = e[0]
				if (this.currentType == 1) { // 周
					this.currentChartsTime = getWeekDate(e[0])
				} else if (this.currentType == 2) { // 月
					this.currentChartsTime = dayjs(e[0]).format('YYYY/MM')
				} else if (this.currentType == 3) { // 年
					this.currentChartsTime = dayjs(e[0]).format('YYYY')
				}
				this.fetchData()
				this.showCalendar = false
			},
			// 上一个选项
			reduceTap() {
				if (this.currentType == 1) {
					let pre = dayjs(dayjs(this.defaultDate[0]).subtract(7, 'day')).format('YYYY/MM/DD')
					let min = dayjs(this.minDate).format('YYYY/MM/DD')
					if (!dayjs(pre).isBefore(min)) { // 比对前一天是否是最小天数的前一天
						this.currentChartsTime = getWeekDate(pre)
						this.defaultDate[0] = pre
						this.fetchData()
					} else {
						uni.showToast({
							title: '已经是最后一页',
							icon: 'none'
						})
					}
				} else if (this.currentType == 2) {
					let pre = dayjs(dayjs(this.defaultDate[0]).subtract(1, 'month')).format('YYYY/MM/DD')
					let min = dayjs(this.minDate).format('YYYY/MM/DD')
					if (!dayjs(pre).isBefore(min)) {
						this.currentChartsTime = dayjs(pre).format('YYYY/MM')
						this.defaultDate[0] = pre
						this.fetchData()
					} else {
						uni.showToast({
							title: '已经是最后一页',
							icon: 'none'
						})
					}
				} else if (this.currentType == 3) {
					let pre = dayjs(dayjs(this.defaultDate[0]).subtract(1, 'year')).format('YYYY/MM/DD')
					let min = dayjs(this.minDate).format('YYYY/MM/DD')
					if (!dayjs(pre).isBefore(min)) {
						this.currentChartsTime = dayjs(pre).format('YYYY')
						this.defaultDate[0] = pre
						this.fetchData()
					} else {
						uni.showToast({
							title: '已经是最后一页',
							icon: 'none'
						})
					}
				}
			},
			// 下一个选项
			plusTap() {
				if (this.currentType == 1) {
					let next = dayjs(dayjs(this.defaultDate[0]).add(7, 'day')).format('YYYY/MM/DD')
					let max = dayjs(this.maxDate).format('YYYY/MM/DD')
					if (!dayjs(next).isAfter(max)) { // 比对后一天是否是最大天数的后一天
						this.currentChartsTime = getWeekDate(next)
						this.defaultDate[0] = next
						this.fetchData()
					} else {
						uni.showToast({
							title: '已经是最后一页',
							icon: 'none'
						})
					}
				} else if (this.currentType == 2) {
					let next = dayjs(dayjs(this.defaultDate[0]).add(1, 'month')).format('YYYY/MM/DD')
					let max = dayjs(this.maxDate).format('YYYY/MM/DD')
					if (!dayjs(next).isAfter(max)) {
						this.currentChartsTime = dayjs(next).format('YYYY/MM')
						this.defaultDate[0] = next
						this.fetchData()
					} else {
						uni.showToast({
							title: '已经是最后一页',
							icon: 'none'
						})
					}
				} else if (this.currentType == 3) {
					let next = dayjs(dayjs(this.defaultDate[0]).add(1, 'year')).format('YYYY/MM/DD')
					let max = dayjs(this.maxDate).format('YYYY/MM/DD')
					if (!dayjs(next).isAfter(max)) {
						this.currentChartsTime = dayjs(next).format('YYYY')
						this.defaultDate[0] = next
						this.fetchData()
					} else {
						uni.showToast({
							title: '已经是最后一页',
							icon: 'none'
						})
					}
				}
			},
			// 更改显示状态tabs状态栏
			changeType(TYPE) {
				this.currentType = TYPE
			},
			getOption(xArr, data, type) {
				// let max = Math.max(...data)
				let max;
				return {
					grid: {
						left: 0,
						right: "5%",
						bottom: 0,
						top: "5%",
						containLabel: true
					},
					dataZoom: type == 'month' ? {
						id: 'ecRecord',
						type: 'inside',
						filterMode: 'none',
						xAxisIndex: 0,
						startValue: 0,
						endValue: this.currentType == 2 ? 10 : 11,
						zoomLock: true
					} : null,
					xAxis: {
						type: 'category',
						axisLine: {
							show: false
						},
						axisLabel: {
							margin: 16,
							color: '#666D7F',
							fontWeight: 'normal',
							fontSize: 10,
							align: 'center'
						},
						axisTick: {
							show: false
						},
						data: xArr
					},
					yAxis: {
						type: 'value',
						splitLine: {
							show: true,
							lineStyle: {
								width: 1,
								color: '#E6EBF5',
								type: 'dashed',
								opacity: .2
							}
						},
						min: 0,
						max: function(value) {
							let surplus = value.max % 10
							if (surplus == 0) {
								max = value.max + 10;
								return max
							} else {
								max = value.max + (10 - surplus);
								return max
							}
						},
						splitNumber: 1,
						axisLabel: {
							margin: 4,
							color: '#666666',
							verticalAlign: 'top',
							formatter: function(value, index) {
								if (value == 0 || value == max) {
									return value
								}
							}
						}
					},
					series: [{
						name: '时长',
						type: 'bar',
						barWidth: 8,
						z: 99,
						itemStyle: {
							color: '#545DDE',
							borderRadius: [4, 4, 0, 0]
						},
						data
					}]
				}
			},
			goRecord() {
				uni.navigateTo({
					url: '/pagesA/health/sleep/record/index'
				})
			},
			getBgColor(data) {
				return getItemColor(data)
			},
			getHeight(data) {
				if (data == 5) {
					return '86rpx'
				} else if (data == 4) {
					return '74rpx'
				} else if (data == 3) {
					return '62rpx'
				} else if (data == 2) {
					return '50rpx'
				} else if (data == 1) {
					return '38rpx'
				}
			},
			getStatusSrc(info) {
				if (info.rerLevelAfter > info.rerLevelFront) {
					return this.status[2]
				} else if (info.rerLevelAfter === info.rerLevelFront) {
					return this.status[1]
				} else if (info.rerLevelAfter < info.rerLevelFront) {
					return this.status[0]
				}
			}
		}
	}
</script>
<style lang="scss">
	page {
		background-color: #FAFAFA;
		min-height: 100%;

		.u-popup__content {
			border-top-left-radius: 128rpx;
		}

		.u-popup__content__close {
			top: 48rpx !important;
			right: 48rpx !important;

			.u-icon__icon {
				font-size: 28rpx !important;
			}
		}
	}
</style>
<style lang="scss" scoped>
	.sleep {
		padding: 0 48rpx 48rpx;

		.m-container {
			.top_view {
				.date_h {
					padding: 48rpx 0 32rpx;

					.date_m {
						background-color: #545DDE;
						color: #fff;
						font-size: 24rpx;
					}

					.next_p,
					.pre_p {
						background-color: #545DDE;
					}

					.iconfont {
						font-size: 18rpx;
						color: #fff;
					}
				}

			}

			.o_s_card {
				padding: 0 32rpx;

				.info {
					height: 172rpx;
				}

				.time {
					font-size: 24rpx;
					color: #666666;
				}

			}

			.none {
				width: 100%;
				height: 124rpx;
				background: #FFFFFF;
				border-radius: 32rpx;
				line-height: 124rpx;
				font-weight: 500;
				font-size: 24rpx;
				color: #666666;
			}

			.r-card {
				margin-top: 32rpx;
				padding: 32rpx 48rpx;

				.tabs {
					padding: 0;
				}

				.charts {
					height: 370rpx;
					margin: 24rpx 0 48rpx;
				}

				.c_tips {
					border-top: 2rpx solid #FAFAFA;
					padding: 32rpx 16rpx 0;
					width: 100%;

					.current_modal {
						width: 100%;
						height: 64rpx;
						padding: 14rpx 32rpx;
						border-radius: 32rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						background-color: #FAFAFA;
						font-size: 24rpx;

						.time {
							width: 49%;
							color: #666666;
							border-right: 2rpx solid #E5E5E5;
							text-align: left;
						}

						.data {
							width: 49%;
							font-weight: 500;
							color: #545DDE;
							font-family: PingFangSC-Medium, PingFang SC;
							text-align: right;
						}
					}
				}

			}

			.tooltip {
				display: flex;
				align-items: flex-start;
				justify-content: space-between;

				.t-l {
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					justify-content: center;

					.mean_txt {
						font-size: 20rpx;
						color: #333333;
					}

					.mean {
						padding: 8rpx 0 32rpx;
						font-weight: 500;
						font-size: 24rpx;
						color: #545DDE;
						font-family: PingFangSC-Medium, PingFang SC;
					}
				}
			}
		}
	}
</style>